﻿using UnityEngine;
using System.Collections;

public class SpriteManipulateNew : MonoBehaviour {

	public SpriteRenderer sprite;
	Color originalColor;
	bool bInit;

	
	void InitSprite()
	{
		if(bInit)
			return;
		bInit = true;
		if(sprite==null)
		{
			sprite = gameObject.GetComponent<SpriteRenderer>();
			if(sprite!=null)
				originalColor = sprite.color;
		}

	}
	
	void SetColor(Color color)
	{
		if(sprite!=null)
			sprite.color = color;
	}
	
	Color GetColor()
	{
		if(sprite!=null)
			return sprite.color;	
		return Color.white;
	}

	public void SetSpriteName(string name)
	{
		InitSprite();
		glog.debug("spritename = "+name);
		if(sprite!=null)
		{
			if( !ChanceSkill.spriteDic.ContainsKey(name) )
			{
				Sprite loadedSprite = ChanceSkill.LoadSkillIcon(name);
				if( loadedSprite != null )
					sprite.sprite = loadedSprite;
			}
			else
			{
				Sprite loadedSprite = ChanceSkill.spriteDic[name];
				if( loadedSprite != null )
					sprite.sprite = loadedSprite;
			}
		}

	}
	
	public void ChangeAlphaDelay(float targetAlpha, float speed, float delay, bool bDestroy)
	{
		InitSprite();
		StartCoroutine(CoChangeAlpha(targetAlpha, speed, delay, bDestroy));
	}
	
	public void ChangeAlpha(float targetAlpha, float speed, bool bDestroy)
	{
		ChangeAlphaDelay(targetAlpha,speed,0,bDestroy);
	}
	
	IEnumerator CoChangeAlpha(float targetAlpha, float speed, float delay, bool bDestroy)
	{
		yield return new WaitForSeconds(delay);
		originalColor = GetColor();
		float alpha_num = 1.0f;
		while(alpha_num>0)
		{
			alpha_num -= speed*Time.deltaTime;
			if(alpha_num <0)
				alpha_num = 0;
			SetColor ( new Color(originalColor.r, originalColor.g, originalColor.b, alpha_num) );
			yield return null;
		}		
		if(bDestroy)
			Destroy(gameObject);
	}
}
